package com.unifiedsearch.utils.utils;

import com.alibaba.fastjson.JSON;
import com.unifiedsearch.utils.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class GetTokenByAuthorizationUtils
{
    public static String getToken() throws IOException
    {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse();

        if(StringUtils.isEmpty(request.getHeader("Authorization")))
        {
            Result result = Result.fail().message("token为空!");
            assert response != null;
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
        }
        return request.getHeader("Authorization");
    }
}
